package com.example.electricbicycle.controller;

import com.example.electricbicycle.po.Customer;
import com.example.electricbicycle.po.User;
import com.example.electricbicycle.service.CustomerService;
import com.example.electricbicycle.service.CustomerServiceImpl;
import com.example.electricbicycle.service.UserService;
import com.example.electricbicycle.service.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@WebServlet("/AdminDashboardServlet")
public class AdminDashboardServlet extends HttpServlet {
    private final CustomerService customerService = new CustomerServiceImpl();
    private final UserService userService = new UserServiceImpl();

    // 使用线程池进行并行数据加载
    private final ExecutorService executorService = Executors.newFixedThreadPool(2);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 使用并行加载提高性能
        Future<List<Customer>> customersFuture = executorService.submit(() ->
                customerService.getAllCustomers(1, 50));

        Future<List<User>> usersFuture = executorService.submit(() ->
                userService.getAllUsers(1, 50));

        try {
            List<Customer> allCustomers = customersFuture.get();
            request.setAttribute("allCustomers", allCustomers);

            List<User> allUsers = usersFuture.get();
            request.setAttribute("allUsers", allUsers);

            // 假数据（为了好看）
            request.setAttribute("saleCompletionRate", 0.75);
            request.setAttribute("weeklyOrders", 28);
            request.setAttribute("pendingAfterSales", 5);
            request.setAttribute("inventoryTurnover", 0.45);

        } catch (Exception e) {
            // 记录错误日志
            e.printStackTrace();

            // 设置默认空
            request.setAttribute("allCustomers", List.of());
            request.setAttribute("allUsers", List.of());

            request.setAttribute("errorMsg", "数据加载失败，请稍后重试");
        }

        request.getRequestDispatcher("/admin/list.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 删除备份功能后，此处仅保留其他POST处理（如果有）
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的操作请求");
    }

    @Override
    public void destroy() {
        executorService.shutdown();
        super.destroy();
    }
}